<template>
  <div class="age-distribution-card">
    <div class="card-title">高血压人群年龄分布</div>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { useDashboardStore } from '../stores/dashboard';

const dashboardStore = useDashboardStore();
const chartContainer = ref(null);
let chart = null;

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;
  
  chart = echarts.init(chartContainer.value);
  updateChart();
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

// 更新图表数据
const updateChart = () => {
  const { categories, series } = dashboardStore.ageChartData;
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 40,
      textStyle: { fontSize: 16 }
    },
    series: [
      {
        name: '人数',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 16,
          borderColor: '#fff',
          borderWidth: 4
        },
        color: [
          '#ff6f91', '#f6d365', '#fda085', '#a1c4fd', '#c2e9fb', '#43e97b', '#38f9d7', '#fa8bff'
        ],
        label: {
          show: true,
          formatter: '{b}: {c}人\n({d}%)',
          fontSize: 16
        },
        labelLine: {
          show: true
        },
        data: categories.map((cat, i) => ({ value: series[i], name: cat }))
      }
    ]
  };
  chart.setOption(option);
};

// 监听数据变化，更新图表
watch(
  () => dashboardStore.ageChartData,
  () => {
    if (chart) {
      updateChart();
    }
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});
</script>

<style scoped>
.age-distribution-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  height: 100%;
}

.card-title {
  font-size: 22px;
  margin-bottom: 24px;
}
.chart-container {
  height: 380px;
}
</style>